package com.tr.demo01;

/**
 * @author TRasdzz
 * @since 2021/3/8 20:32
 * @version 1.0
 */
public class Race implements Runnable{
    //创建一个静态的胜者 保证胜者只有一个（静态的胜者只在类加载的时候加载一次）
    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {

            //如果比赛结束 直接跳出
            if (raceOver(i)){
                break;
            }
            //制裁兔子的方法
            if (Thread.currentThread().getName() == "兔子" && i % 50 == 0 ){
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName() + "已经跑了" + i + "步");
        }
    }

    private boolean raceOver(int steps) {
        if (winner != null){
            return true;
        }
        if (steps >= 100){
            winner = Thread.currentThread().getName();
            System.out.println("winner is " + winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
